package org.elec.mac.controller;

import com.sun.corba.se.spi.ior.ObjectKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.entity.ExecuteResult;
import org.elec.mac.entity.SCategory;
import org.elec.mac.entity.SProduct;
import org.elec.mac.entity.SProduct;
import org.elec.mac.page.PageList;
import org.elec.mac.page.PageProperty;
import org.elec.mac.service.SCategoryService;
import org.elec.mac.service.SProductService;
import org.elec.mac.tag.UserNameTag;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.PriceUtil;
import org.elec.mac.utils.UpFileUtils;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 产品
 * Created by bingren on 2018/3/22.
 */
@Slf4j
@Controller
public class ProductController extends BaseController {

    @Value("${image.path}")
    private String imagepath;

    @Autowired
    private SProductService sProductService;

    @Autowired
    private SCategoryService sCategoryService;

    @RequestMapping(value = "/product_list.do")
    public String productListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                  @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                  @RequestParam(value = "limit", required = false)String limit,
                                  @RequestParam(value = "page", required = false)String page) throws IOException {
        if ("page".equals(action)) {
            PageProperty pp = new PageProperty();
          /*  pp.getParamMap().put("flag", true);*/
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                this.setPageInfo(request.getCookies(), pp, limit, page);
                PageList<Map<String, Object>> lintPageList = sProductService.getPageLists(pp);
                map.put("records", lintPageList.getRecords());
                map.put("recordsTotal", lintPageList.getTotalRecords());
                map.put("recordsFiltered", lintPageList.getTotalRecords());
            }
            catch (Exception ex) {
                log.error("产品列表获取错误", ex);
                map.put("records", null);
                map.put("recordsTotal", 0);
                map.put("recordsFiltered", 0);
            }
            response.getWriter().write(JSONUtil.map2json(map));
            log.info(JSONUtil.map2json(map));

            return null;
        }
        return "/product/product_list";
    }
    //新增产品
   @RequestMapping(value = "/product_add.do")
    public void productAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                   @RequestParam(value = "action", required = false, defaultValue = "")String action) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("do".equals(action)) {
            try {
                String name = this.getParameter(request, "addname");
                String description = this.getParameter(request, "adddescription");
                String pprice = this.getParameter(request, "addpprice");
                String price = this.getParameter(request, "addprice");
                String cidname = this.getParameter(request,"addcid");
                String sweet = this.getParameter(request,"addsweet");
                String temperature = this.getParameter(request,"addtemperature");
                String pearl = this.getParameter(request,"addpearl");
                String materials = sweet + "," + temperature + "," + pearl;
                String[] array = cidname.split("_");
                Long cid = Utils.parseLong(array[0],0);
                String cename = array[1];

                String filename = UpFileUtils.upLoadImageFile(request, imagepath, "addpic");

                if(StringUtils.isBlank(name)) {
                    result.setSuccess(false);
                    result.setMsg("产品名不能为空");
                }
                if(StringUtils.isBlank(description)) {
                    result.setSuccess(false);
                    result.setMsg("产品描述不能为空");
                }
                if(StringUtils.isBlank(price)) {
                    result.setSuccess(false);
                    result.setMsg("产品价格不能为空");
                }
                if(result.isSuccess()) {
                  SProduct sProduct = new SProduct();
                    sProduct.setName(name);
                    sProduct.setDescription(description);
                    sProduct.setCid(cid);
                    sProduct.setCename(cename);
                    sProduct.setPprice(PriceUtil.parse(pprice));
                    sProduct.setPrice(PriceUtil.parse(price));
                    sProduct.setStatus(1);
                    sProduct.setPicpath(filename);
                    sProduct.setMaterials(materials);
                    sProduct.setFlag(true);
                    sProductService.insert(sProduct);
                    log.info("产品新增");
                }
            }
            catch (Exception ex) {
                log.error("产品新增错误", ex);
                result.setSuccess(false);
                result.setMsg("产品新增错误");
            }
        }else {
            Map<String, Object> param = new HashMap<>();
            List<SCategory> sCategoryList = sCategoryService.list(param);
            StringBuilder builder = new StringBuilder();
            if(sCategoryList != null && sCategoryList.size() > 0) {
                builder.append("<option value=\"\">---请选择---</option>");
                for(SCategory sCategory : sCategoryList) {
                    builder.append("<option value=\"" + sCategory.getId() +"_"+ sCategory.getEname() + "\">");
                    builder.append(sCategory.getName());
                    builder.append("</option>");
                }
            }
            result.getBody().put("sCategoryList", builder.toString());
        }

        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    //修改（删除）产品
    @RequestMapping(value = "/product_edit.do")
    public void productEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                    @RequestParam(value = "action", required = false, defaultValue = "")String action,
                                    @RequestParam(value = "id", required = false, defaultValue = "")String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SProduct sProduct = sProductService.get(params);
                result.getBody().put("sProduct", sProduct);
                Map<String, Object> param = new HashMap<>();
                List<SCategory> sCategoryList = sCategoryService.list(param);
                StringBuilder builder = new StringBuilder();
                if(sCategoryList != null && sCategoryList.size() > 0) {
                    builder.append("<option value=\"\">---请选择---</option>");
                    for(SCategory sCategory : sCategoryList) {
                        builder.append("<option value=\"" + sCategory.getId() + "_"+ sCategory.getEname() + "\"");
                        if(sCategory.getId().equals(sProduct.getCid())) {
                            builder.append(" selected=true>");
                        } else {
                            builder.append(">");
                        }
                        builder.append(sCategory.getName());
                        builder.append("</option>");
                    }
                }
                result.getBody().put("sCategoryList", builder.toString());
                log.info("产品修改开启");
            }
            catch (Exception ex) {
                log.error("产品修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("产品修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            try {
                String name = this.getParameter(request, "editname");
                String description = this.getParameter(request, "editdescription");
                Long pprice = PriceUtil.parse(this.getParameter(request, "editpprice"));
                Long price = PriceUtil.parse(this.getParameter(request, "editprice"));
                String cidname = this.getParameter(request,"editcid");
                String[] array = cidname.split("_");
                Long cid = Utils.parseLong(array[0],0);
                String cename = array[1];
                String editpic = UpFileUtils.upLoadImageFile(request,imagepath,"editpic");
                String sweet = this.getParameter(request,"editsweet");
                String temperature = this.getParameter(request,"edittemperature");
                String pearl = this.getParameter(request,"editpearl");
                String materials = sweet + "," + temperature + "," + pearl;

                if(StringUtils.isBlank(name)) {
                    result.setSuccess(false);
                    result.setMsg("产品名不能为空");
                }
                if(StringUtils.isBlank(description)) {
                    result.setSuccess(false);
                    result.setMsg("产品描述不能为空");
                }
                if(price == 0) {
                    result.setSuccess(false);
                    result.setMsg("产品价格不能为空");
                }
                if(result.isSuccess()) {
                    SProduct sProduct = new SProduct();
                    sProduct.setId(Utils.parseLong(id, 0L));
                    sProduct.setName(name);
                    sProduct.setDescription(description);
                    sProduct.setPprice(pprice);
                    sProduct.setPrice(price);
                    sProduct.setStatus(1);
                    sProduct.setCid(cid);
                    sProduct.setCename(cename);
                    sProduct.setFlag(true);
                    sProduct.setMaterials(materials);
                    if(!StringUtils.isBlank(editpic)) {
                        sProduct.setPicpath(editpic);
                    }
                    sProductService.update(sProduct);
                    log.info("产品修改");
                }
            }
            catch (Exception ex) {
                log.error("产品修改错误", ex);
                result.setSuccess(false);
                result.setMsg("产品修改错误");
            }
        }
        if("doDelete".equals(action)) {
            try {
                SProduct sProduct = new SProduct();
                sProduct.setId(Utils.parseLong(id, 0L));
                sProduct.setStatus(0);
                sProduct.setFlag(false);
                sProductService.update(sProduct);
                log.info("产品删除");
            }
            catch (Exception ex) {
                log.error("产品删除错误", ex);
                result.setSuccess(false);
                result.setMsg("产品删除错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
}
